﻿using Avalonia.Collections;
using Avalonia.Styling;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using Material.Icons;
using P2P.Client.Tasks;
using P2P.DB;
using P2P.DB.Model;
using SukiUI;
using SukiUI.Controls;
using SukiUI.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Net.NetworkInformation;
using System.Threading;
using System.Threading.Tasks;

namespace P2P.Client.UI.Features.Server;

public partial class ServerViewModel : PageBase
{
    public AvaloniaList<ServerInfoViewModel> DataGridContent { get; } = new();
    [ObservableProperty] private bool _isDataGridColumnsResizable = true;

    [ObservableProperty] private ServerInfoViewModel _selectedServerInfo = new();

    private TimerTask _timerTask;

    public ServerViewModel() : base("服务器", MaterialIconKind.Server, 1)
    {
        LoadDataFromDb();
    }

    public void LoadDataFromDb() 
    {
        List<ServerModel> resultList = SqliteHelper.GetDb().Queryable<ServerModel>().ToList();

        resultList.ForEach((e) =>
        {
            ServerInfoViewModel serverInfo = new ServerInfoViewModel();
            serverInfo.Id = e.Id;
            serverInfo.ServerName = e.ServerName;
            serverInfo.Ip = e.IP;
            serverInfo.Port = e.Port;
            serverInfo.Desc = e.Desc;
            serverInfo.SelectedPriorityContent = e.Priority;
            serverInfo.Version = e.Version;
            serverInfo.ConnectState = "未连接";
            DataGridContent.Add(serverInfo);
        });

        _timerTask = new TimerTask(() =>
        {
            foreach (var server in DataGridContent)
            {
                PingServer(server);
            }
        },TimeSpan.FromSeconds(1));
    }

    private void PingServer(ServerInfoViewModel serverInfo) 
    {
        try
        {
            Ping ping = new Ping();
            PingReply reply = ping.Send(serverInfo.Ip);

            if (reply.Status == IPStatus.Success)
            {
                serverInfo.Ping = reply.RoundtripTime;
            }
        }
        catch { }
    }

    [RelayCommand]
    private void OpenAddServerInfoDialog() =>
           SukiHost.ShowDialog(new AddServerInfoDialogView(this));

}